package com.zhen.concurrent.chapter07;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class PreventDuplicated {

    private final static String LOCK_PATH = "E:\\";

    private final static String LOCK_FILE = ".lock";

    private final static String PERMISSIONS = "rw-------";

    public static void main(String[] args) throws Exception {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("The program received kill SIGNAL");
            getLockFile().toFile().delete();
        }));
        checkRunning();
        for(;;){
            TimeUnit.SECONDS.sleep(1);
        }
    }

    private static void checkRunning() throws Exception{
        Path path = getLockFile();

        if(path.toFile().exists()){
            throw new RuntimeException("The program already running.");
        }

/*        Set<PosixFilePermission> perms = PosixFilePermissions.fromString(PERMISSIONS);
        Files.createFile(path,PosixFilePermissions.asFileAttribute(perms));*/
        Files.createFile(path);
    }

    private static Path getLockFile(){
        return Paths.get(LOCK_PATH,LOCK_FILE);
    }
}
